package com.yxinsur.imc.business.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxinsur.imc.business.domain.ImcBroker;
import com.yxinsur.imc.business.domain.ImcBrokerRole;
import com.yxinsur.imc.business.domain.ImcBrokerRoleImport;
import com.yxinsur.imc.business.domain.ImcRole;
import com.yxinsur.imc.business.enums.IsDeletedEnum;
import com.yxinsur.imc.business.excel.BrokerRoleTemplate;
import com.yxinsur.imc.business.form.BrokerRoleForm;
import com.yxinsur.imc.business.mapper.ImcBrokerMapper;
import com.yxinsur.imc.business.mapper.ImcBrokerRoleMapper;
import com.yxinsur.imc.business.mapper.ImcRoleMapper;
import com.yxinsur.imc.business.service.IImcBrokerRoleService;
import com.yxinsur.imc.business.vo.BrokerRoleVo;
import com.yxinsur.imc.common.exception.BusinessException;
import com.yxinsur.imc.common.exception.CustomException;
import com.yxinsur.imc.common.utils.DateUtils;
import com.yxinsur.imc.common.utils.SecurityUtils;
import com.yxinsur.imc.common.utils.StringUtils;
import com.yxinsur.imc.common.validator.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 代理人身份角色Service业务层处理
 *
 * @author imc
 * @date 2021-03-19
 */
@Service
public class ImcBrokerRoleServiceImpl extends ServiceImpl<ImcBrokerRoleMapper, ImcBrokerRole> implements IImcBrokerRoleService
{
    @Autowired
    private ImcBrokerRoleMapper imcBrokerRoleMapper;
    @Autowired
    private ImcRoleMapper imcRoleMapper;
    @Autowired
    private ImcBrokerMapper imcBrokerMapper;

    /**
     * 查询代理人身份角色
     *
     * @param id 代理人身份角色ID
     * @return 代理人身份角色
     */
    @Override
    public ImcBrokerRole selectImcBrokerRoleById(String id)
    {
        return imcBrokerRoleMapper.selectImcBrokerRoleById(id);
    }

    /**
     * 查询代理人身份角色列表
     *
     * @param brokerRoleForm 代理人身份角色
     * @return 代理人身份角色
     */
    @Override
    public List<BrokerRoleVo> selectImcBrokerRoleList(BrokerRoleForm brokerRoleForm)
    {
        return imcBrokerRoleMapper.selectImcBrokerRoleList(brokerRoleForm,SecurityUtils.getTenantId());
    }

    /**
     * 新增代理人身份角色
     *
     * @param brokerRoleForm 代理人身份角色
     * @return 结果
     */
    @Override
    public int insertImcBrokerRole(BrokerRoleForm brokerRoleForm)
    {
        ImcBrokerRole imcBrokerRole = new ImcBrokerRole();
        BeanUtils.copyProperties(brokerRoleForm,imcBrokerRole);
        imcBrokerRole.setCreateTime(DateUtils.getNowDate());
        imcBrokerRole.setUpdateTime(DateUtils.getNowDate());
        imcBrokerRole.setCreateId(SecurityUtils.getUsername());
        imcBrokerRole.setUpdateId(SecurityUtils.getUsername());
        imcBrokerRole.setTenantId(SecurityUtils.getTenantId());
        return imcBrokerRoleMapper.insertImcBrokerRole(imcBrokerRole);
    }

    /**
     * 修改代理人身份角色
     *
     * @param imcBrokerRole 代理人身份角色
     * @return 结果
     */
    @Override
    public int updateImcBrokerRole(ImcBrokerRole imcBrokerRole)
    {
        imcBrokerRole.setUpdateTime(DateUtils.getNowDate());
        return imcBrokerRoleMapper.updateImcBrokerRole(imcBrokerRole);
    }

    /**
     * 批量删除代理人身份角色
     *
     * @param ids 需要删除的代理人身份角色ID
     * @return 结果
     */
    @Override
    public int deleteImcBrokerRoleByIds(String[] ids)
    {
        return imcBrokerRoleMapper.deleteImcBrokerRoleByIds(ids);
    }

    /**
     * 删除代理人身份角色信息
     *
     * @param id 代理人身份角色ID
     * @return 结果
     */
    @Override
    public int deleteImcBrokerRoleById(String id)
    {
        return imcBrokerRoleMapper.deleteImcBrokerRoleById(id);
    }

    /**
     * 校验代理人职级信息 职级是否存在
     * @param brokerRoles
     * @return
     */
    @Override
    public HashMap<String, Object> checkBrokerRoles(List<ImcBrokerRoleImport> brokerRoles) {
        HashMap<String, Object> returnMap = new HashMap<>();
        returnMap.put("flag",true);
        StringBuffer buffer = new StringBuffer();
        for (ImcBrokerRoleImport brokerRole : brokerRoles) {
            String roleName = brokerRole.getRoleName();
            ImcRole imcRole = imcRoleMapper.getByRoleName(roleName);
            if(StringUtils.isNull(imcRole)){
                returnMap.put("flag",false);
                buffer.append("</br>导入职级"+roleName+"不存在，请检查");
            }
        }
        returnMap.put("message",buffer.toString());
        return returnMap;
    }

    /**
     * 代理人职级信息导入
     * @param brokerRoles
     * @return
     */
    @Override
    @Transactional
    public String importBrokerRole(List<BrokerRoleTemplate> brokerRoles) {
        Long tenantId = SecurityUtils.getTenantId();
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        QueryWrapper<ImcRole> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("is_deleted", IsDeletedEnum.N.getCode());
        roleQueryWrapper.eq("tenant_id", SecurityUtils.getTenantId());
        List<ImcRole> roles = this.imcRoleMapper.selectList(roleQueryWrapper);
        //职级名称和职级ID字典map
        Map<String,Long> roleMap = new HashMap<>();
        for (ImcRole role:roles) {
            roleMap.put(role.getBrokerRoleName(),role.getId());
        }
        Date date = DateUtils.getNowDate();
        String username = SecurityUtils.getUsername();
        for (BrokerRoleTemplate brokerRole : brokerRoles) {
            try {
                if(StringUtils.isBlank(brokerRole.getBrokerRoleBefore()) && StringUtils.isBlank(brokerRole.getBrokerRoleAfter())){
                    throw new BusinessException("[序号："+brokerRole.getIndex()+"]不允许调整前职级和调整后职级都为空");
                }
                ImcBroker broker = this.imcBrokerMapper.selectImcBrokerByCode(brokerRole.getBrokerCode(),tenantId);
                Assert.isNull(broker,"[序号："+brokerRole.getIndex()+"]代理人工号（"+brokerRole.getBrokerCode()+"）在系统中不存在");
                if(StringUtils.isNotBlank(brokerRole.getBrokerRoleBefore())){
                    Long beforeId = roleMap.get(brokerRole.getBrokerRoleBefore());
                    Assert.isNull(beforeId,"[序号："+brokerRole.getIndex()+"]调整前职级非系统定义的职级名称");
                    UpdateWrapper<ImcBrokerRole> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.lambda().set(ImcBrokerRole::getIsDeleted,IsDeletedEnum.Y.getCode())
                            .set(ImcBrokerRole::getUpdateTime,date)
                            .eq(ImcBrokerRole::getBrokerId,broker.getId())
                            .eq(ImcBrokerRole::getRoleId,beforeId);
                    this.imcBrokerRoleMapper.update(null, updateWrapper);
                }
                if(StringUtils.isNotBlank(brokerRole.getBrokerRoleAfter())){
                    Long afterId = roleMap.get(brokerRole.getBrokerRoleAfter());
                    Assert.isNull(afterId,"[序号："+brokerRole.getIndex()+"]调整后职级非系统定义的职级名称");
                    ImcBrokerRole role = new ImcBrokerRole();
                    role.setBrokerId(broker.getId());
                    role.setRoleId(afterId);
                    role.setBrokerRoleStart(StringUtils.isNotBlank(brokerRole.getBrokerRoleStart())?DateUtils.parseDate(brokerRole.getBrokerRoleStart()):null);
                    role.setCreateId(username);
                    role.setCreateTime(date);
                    role.setRemark(brokerRole.getRemark());
                    role.setIsDeleted(IsDeletedEnum.N.getCode());
                    role.setTenantId(tenantId);
                    this.imcBrokerRoleMapper.insert(role);
                }
                successNum++;
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + brokerRole.getBrokerName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            //保存代理人信息
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
